﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using DFGK.IRepository;
using DFGK.IRepository.BBS;
using DFGK.IService.BBS;
using DFGK_WMS.Common;
using DFGK_WMS.Model.Dto;
using DFGK_WMS.Model.Enum;
using DFGK_WMS.Model.Models.BBS;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;

namespace DFGK.Service.BBS
{
    public class WorkflowService : BaseService, IWorkflowService
    {
        private readonly IUnitOfWork unitOfWork;
        private readonly IWorkflowRepository _workflowRepo;

        private readonly IReceivingBillRepository _receivingBillRepo;
        public WorkflowService(IMapper mapper, IUnitOfWork unitOfWork, IWorkflowRepository workflowRepo, IReceivingBillRepository receivingBillRepo) : base(mapper)
        {
            this.unitOfWork = unitOfWork;
            _workflowRepo = workflowRepo;
            _receivingBillRepo = receivingBillRepo;
        }


        public bool SubmitWorkflow(WorkFlow workFlow, out string errMsg)
        {
            errMsg = "";

            if (workFlow.Id > 0)
            {
                _workflowRepo.UpdEntity(workFlow);
            }
            else
            {
                _workflowRepo.AddEntity(workFlow);
            }
            return unitOfWork.SaveChangesEntity();
        }
        public WorkFlow? GetWorkflow(long workflowId)
        {
            return _workflowRepo.QueryEntityById(workflowId);
        }
        public bool DelWorkflow(long workFlowId, out string errmsg)
        {
            errmsg = "";
            var workFlow = _workflowRepo.QueryEntityById(workFlowId);
            if (workFlow == null)
            {
                errmsg = "参数错误";
            }
            _workflowRepo.DelEntity(workFlow);
            return unitOfWork.SaveChangesEntity();
        }

        public List<WorkFlow> GetWorkFlowPageData(string? busName, string? status, out int totalCount, int pageIndex = 1, int pageSize = 20)
        {
            var query = _workflowRepo.GetEntityAll();
            if (!string.IsNullOrEmpty(busName))
            {
                query = query.Where(t => t.BussinessName.Contains(busName));
            }
            if (status != null && status != "")
            {
                query = query.Where(t => t.Status == status);
            }
            totalCount = query.Count();
            query = query.Skip((pageIndex - 1) * pageSize).Take(pageSize).OrderByDescending(o => o.Id);
            return query.ToList();
        }

        public bool SubmitWorkFlowOrder(WorkFlowAduitInputModel workFlowAduitInput, int cuurentUserId, string? currentUserName, out string errorMsg)
        {
            errorMsg = "";
            var aduitValues = typeof(EmAduitBusinessType).EnumToDictionary().Select(t => Convert.ToInt32(t.Key)).ToList();
            if (!aduitValues.Contains(workFlowAduitInput.AduitType) || workFlowAduitInput.OrderId <= 0)
            {
                errorMsg = "参数错误";
                return false;
            }
            var currentworkFlow = _workflowRepo.QueryEntityWhere(t => t.OrderValue == workFlowAduitInput.AduitType);
            if (currentworkFlow == null)
            {
                errorMsg = "未定义审批流程！";
                return false;
            }
            int aduit = 0;
            int type = workFlowAduitInput.AduitType;
            List<AduitNode> aduitContent = JsonConvert.DeserializeObject<List<AduitNode>>(currentworkFlow.Content);
            int maxAduit = aduitContent.Max(t => t.Sort);
            bool isSkip = aduitContent == null || aduitContent.Count == 0;
            if (type == (int)EmAduitBusinessType.In)
            {
                var order = _receivingBillRepo.QueryEntityById(workFlowAduitInput.OrderId);
                int currentId = order.CurrentAduitId ?? 0;
                if (currentId == 0)
                {
                    if (aduitContent.OrderBy(t => t.Sort).FirstOrDefault().SortId != cuurentUserId)
                    {
                        errorMsg = $"当前登录人ID:{cuurentUserId}，应登录人id：{aduitContent.OrderBy(t => t.Sort).FirstOrDefault().SortId}，审批失败";
                        return false;
                    }
                    order.CurrentAduitId = cuurentUserId;
                    order.CurrentAduitName = currentUserName;
                }
                else
                {
                    if (aduitContent.Count > 1)
                    {
                        var SotId = aduitContent.Where(t => t.SortId == currentId).FirstOrDefault().SortId;
                        var next = aduitContent.Where(t => t.SortId > SotId).OrderBy(t => t.Sort).FirstOrDefault();
                        order.CurrentAduitId = next.SortId;
                        order.CurrentAduitName = next.SortName;
                    }
                    

                    if (order.CurrentAduitId != cuurentUserId)
                    {

                        errorMsg = $"当前登录人ID:{cuurentUserId}，应登录人id：{order.CurrentAduitId}，审批失败";
                        return false;
                    }

                }
                if (order.AduitStatus == 3 || order.AduitStatus == 2)
                {
                    errorMsg = "当前订单审批已经结束";
                    return false;
                }
                if (workFlowAduitInput.ApprovalOpinion == 1)
                {

                    if (aduitContent.OrderByDescending(t => t.Sort).FirstOrDefault().SortId == order.CurrentAduitId)
                    {
                        order.AduitStatus = 2;   //同意
                    }
                    else
                    {
                        order.AduitStatus = 1; //继续审批 
                    }
                }
                else
                {
                    order.AduitStatus = 3; //拒绝
                }
                _receivingBillRepo.UpdEntity(order);
                unitOfWork.SaveChangesEntity();
            }
            return true;

        }
    }

    public class AduitNode
    {
        /// <summary>
        /// 审批顺序
        /// </summary>
        public int Sort { get; set; }
        /// <summary>
        /// 审批人ID
        /// </summary>
        public int SortId { get; set; }
        /// <summary>
        /// 审批人姓名
        /// </summary>
        public string? SortName { get; set; }
        /// <summary>
        /// 条件字段
        /// </summary>
        public string? ConditionField { get; set; }
        /// <summary>
        /// 条件字段值
        /// </summary>
        public string? ConditionValue { get; set; }
        /// <summary>
        /// 条件字段比较符
        /// </summary>
        public string? ConditionCompare { get; set; }
    }
}
